<script setup lang="ts">
import {
  AddInterfaceInfo,
  DeleteById,
  GetInterfaceInfoList,
  UpdateInterfaceInfo,
  OnlineInterfaceInfo,
  OfflineInterfaceInfo
} from "@/api/interfaceInfo";
import {message} from "@/utils/message";
import {markRaw, onMounted, Ref, ref} from "vue";
import {ElInput, ElMessage, ElMessageBox} from "element-plus";
import {Delete} from "@element-plus/icons-vue";
import {InterfaceInfo, InterfaceInfoQueryRequest} from "@/model/interfaceInfo";
import {Page} from "@/model/comon";
import Search from "@iconify-icons/ep/search";

defineOptions({
  name: "InterfaceInfoManage"
});

const interfaceInfoQuery: Ref<InterfaceInfoQueryRequest> = ref({
  /**
   * 当前页号
   */
  current: 1,
  /**
   * 页面大小
   */
  pageSize: 10
});

const pageInterfaceInfoList: Ref<Page<InterfaceInfo>> = ref({});

// 初始化接口数据数据
const getAllInterfaceInfo = async () => {
  const res = await GetInterfaceInfoList(interfaceInfoQuery.value);
  if (res.code === 0) {
    pageInterfaceInfoList.value = res.data;
  } else {
    message(res.message, {type: "error"});
  }
};

// 删除确认框
const deleteUser = id => {
  ElMessageBox.confirm("注意，此操作不可撤销，是否继续？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    icon: markRaw(Delete),
    draggable: true
  })
    .then(async () => {
      // 删除接口
      const res = await DeleteById(id);
      if (res.code === 0) {
        message("删除成功", {type: "success"});
        getAllInterfaceInfo();
      } else {
        message(res.message, {type: "error"});
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

// 搜索接口关键词
const searchKeyword = ref("");
// 处理搜索操作
const handleSearch = () => {
  // 将搜索关键词整合进查询请求对象
  interfaceInfoQuery.value.name = searchKeyword.value.trim();
  // 重置当前页为第一页，因为搜索可能改变结果集
  interfaceInfoQuery.value.current = 1;
  // 执行查询以获取符合搜索条件的用户列表
  getAllInterfaceInfo();
};

// 编辑接口信息
const editFormVisible = ref(false);
const formLabelWidth = "100px";
// 当前修改接口
const currentInterfaceInfo = ref({} as InterfaceInfo);
// 接口状态选项
const statusOptions = [
  {
    value: 1,
    label: "开启"
  },
  {
    value: 0,
    label: "关闭"
  }
];
// 修改用户对话框
const editUser = (interfaceInfo: InterfaceInfo) => {
  editFormVisible.value = true;
  currentInterfaceInfo.value = Object.assign({}, interfaceInfo);
};
// 取消修改
const cancelEdit = () => {
  editFormVisible.value = false;
  currentInterfaceInfo.value = {} as InterfaceInfo;
};
// 确认修改
const confirmEdit = async () => {
  const res = await UpdateInterfaceInfo(currentInterfaceInfo.value);
  if (res.code === 0) {
    message("修改成功", {type: "success"});
    await getAllInterfaceInfo();
    cancelEdit();
  } else {
    message(res.message, {type: "error"});
  }
};
/**
 * 分页
 */
const handleSizeChange = (val: number) => {
  interfaceInfoQuery.value.pageSize = val;
  interfaceInfoQuery.value.current = 1;
  getAllInterfaceInfo();
};
const handleCurrentChange = (val: number) => {
  interfaceInfoQuery.value.current = val;
  getAllInterfaceInfo();
};

onMounted(() => {
  getAllInterfaceInfo();
});

/**
 * 新增接口信息
 */
const showAddDialog = ref(false);
const addInterfaceInfo: Ref<InterfaceInfo> = ref({});

const showAdd = () => {
  showAddDialog.value = true;
};

const closeAdd = () => {
  showAddDialog.value = false;
  addInterfaceInfo.value = {id: 0};
};

const confirmAdd = async () => {
  showAddDialog.value = false;
  const res = await AddInterfaceInfo(addInterfaceInfo.value);
  if (res.code !== 0) {
    return ElMessage.error(res.message);
  }
  addInterfaceInfo.value = {id: 0};
  ElMessage.success("添加成功");
  await getAllInterfaceInfo();
};

const updateStatus = async (id: number, status: number) => {
  // 点击的时候 status 的状态就已经修改了
  if (status === 0) {
    const res = await OfflineInterfaceInfo(id);
    if (res.code !== 0) {
      return ElMessage.error(res.message);
    }
    ElMessage.success("接口下线成功");
  }
  if (status === 1) {
    const res = await OnlineInterfaceInfo(id);
    if (res.code !== 0) {
      return ElMessage.error(res.message);
    }
    ElMessage.success("接口上线成功");
  }
  await getAllInterfaceInfo();
};

</script>

<template>
  <div>
    <el-card class="box-card">
      <el-row style="margin-bottom: 30px">
        <el-col :span="10">
          <el-input
            style="padding-left: 20px !important;"
            v-model="searchKeyword"
            placeholder="请输入接口名称搜索"
            clearable
            @keyup.enter.native="handleSearch"
          >
            <template #suffix>
              <el-icon class="el-input__icon">
                <IconifyIconOffline
                  v-show="searchKeyword.length === 0"
                  :icon="Search"
                />
              </el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button style="margin-left: 20px;width: 70px" type="primary" @click="handleSearch">搜索</el-button>
        </el-col>
        <el-col :span="5"/>
        <el-col :span="3">
          <!--      新增按钮-->
          <el-button
            type="primary"
            size="large"
            style="font-size: 16px; margin: 0 20px 20px 0"
            plain
            @click="showAdd"
          >+ 新增接口信息
          </el-button
          >
        </el-col>
      </el-row>

      <!--  展示表格-->
      <el-table
        :data="pageInterfaceInfoList?.records"
        style="width: 100%"
        table-layout="auto"
      >
        <el-table-column fixed type="index" :index="1"/>
        <el-table-column width="150" fixed prop="name" label="接口名称"/>
        <el-table-column width="150" prop="description" label="接口描述"/>
        <el-table-column width="150" prop="host" label="主机地址"/>
        <el-table-column width="250" prop="url" label="接口地址"/>
        <el-table-column width="150" prop="method" label="请求类型"/>
        <el-table-column width="200" prop="requestParams" label="请求参数"/>
        <el-table-column width="200" prop="requestHeader" label="请求头"/>
        <el-table-column width="200" prop="responseHeader" label="响应头"/>
        <!--    接口状态-->
        <el-table-column label="接口状态">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              inline-prompt
              :active-value=1
              :inactive-value=0
              active-text="开启"
              inactive-text="关闭"
              @change="updateStatus(scope.row.id, scope.row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="user.userName" label="创建人"/>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column width="150" fixed="right" label="操作">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="editUser(scope.row)"
            >编辑
            </el-button
            >
            <el-button
              link
              type="danger"
              @click="deleteUser(scope.row.id)"
            >删除
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!--  底部分页选择-->
      <el-pagination
        style="margin-top: 25px;display: flex;justify-content: flex-end;"
        v-model:current-page="pageInterfaceInfoList.current"
        v-model:page-size="pageInterfaceInfoList.size"
        :page-sizes="[5, 10, 15, 20]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :page-count="parseInt(pageInterfaceInfoList.pages)"
        :total="parseInt(pageInterfaceInfoList.total)"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!--  编辑信息对话框-->
    <el-dialog
      v-model="editFormVisible"
      title="编辑接口信息"
      style="width: 580px"
    >
      <el-form :model="currentInterfaceInfo">
        <el-form-item label="接口名称" :label-width="formLabelWidth">
          <el-input v-model="currentInterfaceInfo.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="接口描述" :label-width="formLabelWidth">
          <el-input v-model="currentInterfaceInfo.description" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="主机地址" :label-width="formLabelWidth">
          <el-input v-model="currentInterfaceInfo.host" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="接口地址" :label-width="formLabelWidth">
          <el-input v-model="currentInterfaceInfo.url" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="请求类型" :label-width="formLabelWidth">
          <el-input v-model="currentInterfaceInfo.method" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="请求参数" :label-width="formLabelWidth">
          <el-input v-model="currentInterfaceInfo.requestParams" autocomplete="off" :rows="4" type="textarea"/>
        </el-form-item>
        <el-form-item label="请求头" :label-width="formLabelWidth">
          <el-input v-model="currentInterfaceInfo.requestHeader" autocomplete="off" :rows="4" type="textarea"/>
        </el-form-item>
        <el-form-item label="响应头" :label-width="formLabelWidth">
          <el-input v-model="currentInterfaceInfo.responseHeader" autocomplete="off" :rows="4" type="textarea"/>
        </el-form-item>

        <!--      接口状态-->
        <el-form-item label="接口状态" :label-width="formLabelWidth">
          <el-select v-model="currentInterfaceInfo.status" placeholder="Select">
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="confirmEdit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!--    新增接口信息-->
    <el-dialog
      v-model="showAddDialog"
      title="新增接口信息"
      width="30%"
      center
      draggable
    >
      <el-form
        label-position="right"
        label-width="80px"
        :model="addInterfaceInfo"
        style="max-width: 460px"
      >
        <el-form-item label="接口名称" :label-width="formLabelWidth">
          <el-input v-model="addInterfaceInfo.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="接口描述" :label-width="formLabelWidth">
          <el-input v-model="addInterfaceInfo.description" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="主机地址" :label-width="formLabelWidth">
          <el-input v-model="addInterfaceInfo.host" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="接口地址" :label-width="formLabelWidth">
          <el-input v-model="addInterfaceInfo.url" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="请求类型" :label-width="formLabelWidth">
          <el-input v-model="addInterfaceInfo.method" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="请求参数" :label-width="formLabelWidth">
          <el-input v-model="addInterfaceInfo.requestParams" autocomplete="off" :rows="4" type="textarea"/>
        </el-form-item>
        <el-form-item label="请求头" :label-width="formLabelWidth">
          <el-input v-model="addInterfaceInfo.requestHeader" autocomplete="off" :rows="4" type="textarea"/>
        </el-form-item>
        <el-form-item label="响应头" :label-width="formLabelWidth">
          <el-input v-model="addInterfaceInfo.responseHeader" autocomplete="off" :rows="4" type="textarea"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAdd">取消</el-button>
          <el-button type="primary" @click="confirmAdd"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
